<?php

Yii::import('application.modules.menu.utililies.menuService');
Yii::import('application.modules.user.models.User');

class OrdersController extends ControllerBase {

    public function init() {
        parent::init();
        $this->defaultAction = 'admin';
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Orders;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Orders'])) {
            $model->attributes = $_POST['Orders'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->orderid));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Orders'])) {
            $model->attributes = $_POST['Orders'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->orderid));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionView($id) {
        $orderDetail = Orderdetail::model()->findAll(array(
            'select' => 't.*, drinkname, count(t.drinkid) as total',
            'join' => 'JOIN drink ON drink.drinkid = t.drinkid',
            'condition' => 't.orderid = :orderid',
            'params' => array(
                ':orderid' => intval($id),
            ),
            'group' => 't.drinkid, syruplist, materiallist',
                ));

        $order = Orders::model()->find(array(
            'condition' => 'orderid = :orderid',
            'params' => array(
                ':orderid' => intval($id),
            )
                ));

        $this->render('view', array(
            'orderDetail' => $orderDetail,
            'order' => $order,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Orders');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Orders('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Orders']))
            $model->attributes = $_GET['Orders'];

        $this->render('admin', array(
            'model' => $model,
            'amountCoffees' => '3'
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Orders::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'orders-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionOrderStatistics() {
        $orders = Orders::model()->findAll();
        $orderDetails = Orderdetail::model()->findAll();

        $this->render('orderStatistics', array(
            'orders' => $orders,
            'orderDetails' => $orderDetails
        ));
    }

    public function actionStatisticsCupsOfCoffee() {
        $orders = Orders::model();

        //get statistics option
        $statisticsOption = isset($_POST['statistics_options']) ? $_POST['statistics_options'] : 'week';

        $criteria = new CDbCriteria();
        $criteria->select = "*";

        $amounts = 0;
        if ((isset($_POST['fromDate']) || isset($_POST['toDate'])) && ($_POST['toDate'] != '' && $_POST['fromDate'] != '')) {
            $fromDate = Util::foramtInputDate($_POST['fromDate']);
            $toDate = Util::foramtInputDate($_POST['toDate']);
            $criteria->condition = 'orderdate between ' . strtotime($fromDate) . " AND " . strtotime($toDate);
        } else if (isset($_POST['fromDate']) && $_POST['fromDate'] != '') {  //get cups beteen current ween, began in Monday ended by Sunday
            $fromDate = Util::foramtInputDate($_POST['fromDate']);
            $toDate = Util::foramtInputDate($_POST['toDate']);
            $week = date('W', strtotime($fromDate));
            $d = Util::getDaysInWeek($week, date('Y', time()));

            if ($statisticsOption == 'week') {
                $criteria->condition = 'orderdate between ' . ($d[0] + 86399) . ' AND ' . ($d[6] + 86399);
            } else if ($statisticsOption == 'day') {
                $criteria->condition = 'orderdate between ' . $d[(date('N', time()) - 1)] . ' AND ' . ($d[(date('N', time()) - 1)] + 84399);
            } else if ($statisticsOption == 'month') {
                $first_minute = mktime(0, 0, 0, date('m', strtotime($fromDate)), 1);
                $last_minute = mktime(23, 59, 0, date('m', strtotime($fromDate)), date('t', $first_minute));

                $criteria->condition = 'orderdate between ' . $first_minute . ' AND ' . $last_minute;
            } else if ($statisticsOption == 'year') {
                $first_minute = mktime(0, 0, 0, 1, 1, date('Y', strtotime($fromDate)));
                $last_minute = mktime(23, 59, 59, 12, 31, date('Y', strtotime($fromDate)));

                $criteria->condition = 'orderdate between ' . $first_minute . ' AND ' . $last_minute;
            }
        }

        $this->render('orderStatistics', array(
            'orders' => $orders->findAll($criteria),
            'statisticsOption' => $statisticsOption,
            'fromDate' => strtotime($fromDate),
            'toDate' => strtotime($toDate),
            'user' => $_POST['user'],
        ));
    }

    public function actionSyncOrders($syncOrderFileName) {
//            $orders = CJSON::decode($this->actionGenerateOrder());
//        $syncOrderFileName = $_GET['order'];
//        $ordersList = Yii::getPathOfAlias('webroot') . "/uploads/orders/orderList.txt";
        $ordersList = Yii::getPathOfAlias('webroot') . "/uploads/orders/" . $syncOrderFileName;
        if (file_exists($ordersList)) {
            $f = fopen($ordersList, 'r');
            $orders = file_get_contents($ordersList);
            foreach ($orders as $order => $value) {  //$value is a order detail and order infor, $order is orderid
                $orderid = $order;
                foreach ($value as $key => $val) {
                    if (is_array($val)) { //read order detail
                        foreach ($val as $k => $v) {
                            $orderDetailModel = new Orderdetail;
                            $orderDetailModel->orderid = $orderid;
                            $orderDetailModel->drinkid = $v['drinkid'];
                            $orderDetailModel->materiallist = $v['materiallist'];
                            $orderDetailModel->syruplist = $v['syruplist'];
                            $orderDetailModel->save();
                            var_dump($orderDetailModel->getErrors());
                        }
                    } else {
                        $orderModel = new Orders();
                        //check order just insert once
                        $exitedOrder = $orderModel->find(array(
                            'condition' => 'orderid = :orderid',
                            'params' => array(
                                ':orderid' => $orderid,
                            )
                                )
                        );

                        if ($exitedOrder === null) {
                            $orderModel->orderid = $orderid;
                            $orderModel->userid = $value['userid'];
                            $orderModel->orderdate = $value['orderdate'];
                            $orderModel->synced = 0;

                            $orderMnodel->note = $value['note'];
                            if (!$orderModel->save()) {
//                                var_dump($orderModel->getErrors());
                                exit(0);
                            }
                        }
                    }
                }
            }
            return CJSON::encode(array('sync order' => true));
        }else
            return CJSON::encode(array('sync order' => false));
    }

    public function actionGenerateOrder() {
        /* $orders = array(
          1 => array(
          'orderdate' => time(),
          'userid' => 1,
          'note' => 'More material in drink ...',
          'detail' => array(
          '1_4' => array(
          'orderid' => 1,
          'drinkid' => 4,
          'materiallist' => '{}',
          'syruplist' => '{}'
          ),
          '1_5' => array(
          'orderid' => 1,
          'drinkid' => 5,
          'materiallist' => '{}',
          'syruplist' => '{}'
          ),
          )
          ),
          2 => array(
          'orderdate' => time(),
          'userid' => 1,
          'note' => 'More materials in drink ...',
          'detail' => array(
          '2_-1' => array(
          'orderid' => 2,
          'drinkid' => 3,
          'materiallist' => '{"50":"1","51":"1","74":"2","1":"1"}',
          'syruplist' => '{"3":"3","24":"1"}'
          ),
          '2_2' => array(
          'orderid' => 2,
          'drinkid' => 2,
          'materiallist' => '{}',
          'syruplist' => '{}'
          ),
          '2_-1' => array(
          'orderid' => 2,
          'drinkid' => 14,
          'materiallist' => '{"0":"1","5":"2","53":"5","1":"1"}',
          'syruplist' => '{}'
          ),
          '2_7' => array(
          'orderid' => 2,
          'drinkid' => 7,
          'materiallist' => '{}',
          'syruplist' => '{}'
          ),
          '2_7' => array(
          'orderid' => 2,
          'drinkid' => 7,
          'materiallist' => '{}',
          'syruplist' => '{}'
          ),
          )
          )
          }
          ); */
        $orders = array(
            1 => array(
                'orderdate' => time(),
                'userid' => 1,
                'note' => 'More material in drink ...',
                'detail' => array(
                    '0' => array(
                        'orderid' => 1,
                        'drinkid' => 4,
                        'materiallist' => '{}',
                        'syruplist' => '{}'
                    ),
                    '1' => array(
                        'orderid' => 1,
                        'drinkid' => 5,
                        'materiallist' => '{}',
                        'syruplist' => '{}'
                    ),
                )
            ),
            2 => array(
                'orderdate' => time(),
                'userid' => 1,
                'note' => 'More materials in drink ...',
                'detail' => array(
                    '0' => array(
                        'orderid' => 2,
                        'drinkid' => 3,
                        'materiallist' => '{"50":"1","51":"1","74":"2","1":"1"}',
                        'syruplist' => '{"3":"3","24":"1"}'
                    ),
                    '1' => array(
                        'orderid' => 2,
                        'drinkid' => 2,
                        'materiallist' => '{}',
                        'syruplist' => '{}'
                    ),
                    '2' => array(
                        'orderid' => 2,
                        'drinkid' => 14,
                        'materiallist' => '{"0":"1","5":"2","53":"5","1":"1"}',
                        'syruplist' => '{}'
                    ),
                    '3' => array(
                        'orderid' => 2,
                        'drinkid' => 7,
                        'materiallist' => '{}',
                        'syruplist' => '{}'
                    ),
                    '4' => array(
                        'orderid' => 2,
                        'drinkid' => 7,
                        'materiallist' => '{}',
                        'syruplist' => '{}'
                    ),
                )
                ));
        echo "<pre>";
        print_r($orders);
        echo "</pre>";
//        echo CJSON::encode($orders);
    }

    public function actionTriggerSyncOrder() {
        $order = isset($_GET['orderFileName']) ? $_GET['orderFileName'] : null;
        if (!is_null($order)) {
            if (file_exists(Yii::getPathOfAlias('webroot') . "/uploads/orders/" . $order . ".txt"))
                $this->actionSyncOrders($order . ".txt");
            else {
                echo CJSON::encode(array('sync order' => false));
                exit(0);
            }
        } else {
            echo CJSON::encode(array('sync order' => false));
            exit(0);
        }
    }

    public function beforeAction($action) {
        parent::beforeAction($action);
        if (Yii::app()->user->id === null)
            $this->redirect(Yii::app()->createUrl('site/login'));
        return true;
        $this->redirect(Yii::app()->createUrl('site/login'));
    }

    public function actionDropBoxSync() {
        Yii::import('application.extensions.base32.*');
        Yii::import('application.extensions.Dropbox');
                
        // Set error reporting
        error_reporting(-1);
        ini_set('display_errors', 'On');
        ini_set('html_errors', 'On');

        // Register a simple autoload function
        spl_autoload_register(function($class) {
                    $class = str_replace('\\', '/', $class);
                    require_once($class . '.php');
                });

        // Set your consumer key, secret and callback URL
        $key = 'x6mq452pubigiw2';
        $secret = '7kddxm1if8nk04s';

        // Check whether to use HTTPS and set the callback URL
        $protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
        $callback = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        $secretCode = Util::base32_encode("centralfrescocoffees");
        
//        var_dump(mb_strlen($secretCode, '8bit'));
        
        // Instantiate the Encrypter and storage objects
        $encrypter = new \Dropbox\OAuth\Storage\Encrypter($secretCode);

        // Create the storage object, passing it the Encrypter object
        $storage = new \Dropbox\OAuth\Storage\Session($encrypter);

        $OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
//        $dropbox = new \Dropbox\API($OAuth);
        
        // Retrieve the account information
//        $accountInfo = $dropbox->accountInfo();

        // Dump the output
//        var_dump($accountInfo);
    }

}